package org.study.hadoop.md.ch5;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.study.hadoop.md.util.MRDPUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

/**
 * 复制连接：给定一个小的用户信息数据集和一个大的评论数据集，通过用户数据来丰富评论的内容
 */
public class ReplicatedJoinDriver extends Configured implements Tool {

    public static class ReplicatedJoinMapper extends Mapper<Object, Text, Text, Text> {
        private HashMap<String, String> userIdToInfo = new HashMap<String, String>();
        private Text outValue = new Text();
        private String joinType = null;

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            try {
                Path[] files = DistributedCache.getLocalCacheFiles(context.getConfiguration());
                if (files == null || files.length == 0) {
                    throw new RuntimeException("User information is not set in DistributedCache");
                }
                for (Path p : files) {
                    BufferedReader rdr = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(new File(p.toString())))));
                    String line;
                    while ((line = rdr.readLine()) != null) {
                        Map<String, String> parsed = MRDPUtils.transformXmlToMap(line);
                        String userId = parsed.get("Id");
                        if (userId != null) {
                            userIdToInfo.put(userId, line);
                        }
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            joinType = context.getConfiguration().get("join.type");
        }

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());
            String userId = parsed.get("UserId");
            if (userId == null) {
                return;
            }
            String userInfomation = userIdToInfo.get(userId);
            if (userInfomation != null) {
                outValue.set(userInfomation);
                context.write(value, outValue);
            } else if (joinType.equalsIgnoreCase("left_outer")) {
                context.write(value, new Text("NULL"));
            }
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Path outPath = new Path("out");
        Path inPath1 = new Path("F:\\user.txt");
        Path inPath2 = new Path("comment.txt");
        FileSystem fs = outPath.getFileSystem(getConf());
        if (fs.exists(outPath)) {
            fs.delete(outPath, true);
        }
        String joinType = "left_outer";
        Job job = Job.getInstance(getConf(), "Replicated Join");
        job.getConfiguration().set("join.type", joinType);
        job.setJarByClass(ReplicatedJoinDriver.class);

        job.setMapperClass(ReplicatedJoinMapper.class);
        job.setNumReduceTasks(0);

        TextInputFormat.setInputPaths(job, inPath2);
        TextOutputFormat.setOutputPath(job, outPath);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        DistributedCache.addCacheFile(inPath1.toUri(), job.getConfiguration());
        DistributedCache.setLocalFiles(job.getConfiguration(), "F:\\user.txt");
        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new ReplicatedJoinDriver(), args);
        System.exit(res);
    }
}
